<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #menu="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :treeData="treeData"
          :replaceFields="{ title: 'menuName', key: 'menuId' }"
          checkable
          toolbar
          title="菜单分配"
        />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './role.data';
  import { listApi } from '/@/api/set/menu';
  import { AddApi, EditApi } from '/@/api/set/role';
  import { listToTree } from '/@/utils/helper/treeHelper';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  import { appStore } from '/@/store/modules/app';
  export default defineComponent({
    name: 'RoleModal',
    components: { BasicModal, BasicForm, BasicTree },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const treeData = ref<TreeItem[]>([]);

      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          const record = data.record;
          record.roleSort = parseInt(record.roleSort);
          setFieldsValue({
            ...data.record,
          });
        }
        treeData.value = (await queryList()) as any as TreeItem[];
      });

      async function queryList() {
        const data = await listApi({ webType: appStore.getAppType });
        if (data.data) {
          return listToTree(data.data, {
            id: 'menuId',
            pid: 'parentId',
            children: 'parentId',
          });
        }
        return [];
      }

      const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });
          const values = await validate();
          if (values.roleId) {
            await EditApi(values);
          } else {
            await AddApi(values);
          }
          closeModal();
          emit('success');
        } catch (err) {
          console.log(err);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerModal,
        registerForm,
        getTitle,
        handleSubmit,
        treeData,
      };
    },
  });
</script>
